简单员工数据库后台sqlite
public class DBAdapter {
private static final String DB_NAME = "people.db";
private static final String DB_TABLE = "peopleinfo";
private static final int DB_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_SEX = "sex";
public static final String KEY_DEPARTMENT = "department";
public static final String KEY_SALARY = "salary";
private SQLiteDatabase db;
private final Context context;
private DBOpenHelper dbOpenHelper;
private static class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String DB_CREATE = "create table " DB_TABLE " (" KEY_ID
" integer primary key autoincrement, " KEY_NAME " text not null, " KEY_SEX " text,"
KEY_DEPARTMENT " text," KEY_SALARY " float);";
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " DB_TABLE);
onCreate(_db);
}
}
public DBAdapter(Context _context) {
context = _context;
}
public void open() throws SQLiteException {
dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
try {
db = dbOpenHelper.getWritableDatabase();
} catch (SQLiteException ex) {
db = dbOpenHelper.getReadableDatabase();
}
}
public void close() {
if (db != null) {
db.close();
db = null;
}
}
public long insert(People people) {
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, people.name);
newValues.put(KEY_SEX, people.sex);
newValues.put(KEY_DEPARTMENT, people.department);
newValues.put(KEY_SALARY, people.salary);
return db.insert(DB_TABLE, null, newValues);
}
public long deleteAllData() {
return db.delete(DB_TABLE, null, null);
}
public long deleteOneData(long id) {
return db.delete(DB_TABLE, KEY_ID "=" id, null);
}
public People[] queryAllData() {
Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_SEX, KEY_DEPARTMENT, KEY_SALARY },
null, null, null, null, null);
return ConvertToPeople(results);
}
评论